package cn.snailhd.admin.novel.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cn.snailhd.admin.novel.domain.CrawlerNovel;
import cn.snailhd.admin.novel.domain.NovelChapter;
import cn.snailhd.admin.novel.service.NovelService;
import cn.snailhd.core.base.dao.MyBatisDao;
import cn.snailhd.core.base.domain.BaseResultDTO;
import cn.snailhd.core.base.domain.PageVo;
import cn.snailhd.utils.RegexUtils;
import cn.snailhd.utils.mail.Mail;
import cn.snailhd.utils.string.StringUtils;


@Controller
@RequestMapping("/novel")
public class NovelController {
	Log log = LogFactory.getLog(this.getClass());

	private final NovelService novelService;
	
	@Resource
	MyBatisDao dao;

    @Autowired
	public NovelController(NovelService novelService){
        this.novelService = novelService;
    }


    /**
     * 查询小说列表
     * @param map
     * @return String
     * @throws IOException
     */
	@ResponseBody
	@RequestMapping(value="/queryNovelList")
	public String queryNovelList(@RequestBody Map params) throws IOException {

		log.info(JSON.toJSONString(params));
		BaseResultDTO re = new BaseResultDTO();
		PageVo<CrawlerNovel> pv = novelService.queryNovelList(params);
		re.setResult(pv);
		re.setSuccess();

		log.info(re);
		return re.toJSON();
	}
	
	
	
	


	/**
	 * 查询小说详情
	 * @param id
	 * @return
	 * @throws IOException
	 */
	@ResponseBody
	@RequestMapping(value="/queryNovelById/{id}")
	public String queryNovelById(@PathVariable String id) throws IOException {
		log.info(JSON.toJSONString("id:"+id));
		
		BaseResultDTO re = new BaseResultDTO();
		CrawlerNovel bean = novelService.queryNovelById(id);
		re.setResult(bean);
		re.setSuccess();	

		log.info(re);
		return re.toJSON();
	}


	/**
	 * 保存小说爬取配置
	 * @param cra
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value="/save",method = RequestMethod.POST)
	public String save(@RequestBody CrawlerNovel cra ) throws Exception {
		BaseResultDTO re = new BaseResultDTO();
		
		String id =cra.getId();
		int flag = 0;
		if(StringUtils.isNotBlank(id)&& null!= novelService.queryNovelById(id)) {
			cra.parse();
			flag = novelService.updateNovel(cra);
		}else {
			cra.parse();
			flag =novelService.addNovel(cra);
		}
		if(flag>0) {
			CrawlerNovel info = novelService.queryNovelById(cra.getId());
			novelService.addChapter(cra);
			re.setResult(cra);
			re.setSuccess();
		}else{
			re.setError();
		}

		return re.toJSON();
	}



	@ResponseBody
	@RequestMapping(value="/del/{id}")
	public String del(@PathVariable String id){
		BaseResultDTO re = new BaseResultDTO();

		JSONArray list = new JSONArray();
		JSONObject obj = new JSONObject();
		obj.put("id",id);
		list.add(obj);
		if(novelService.delNovel(list)>0){
			re.setSuccess();
		}else{
			re.setError("删除失败");
		}
		
		return re.toJSON();
	}
	
	

	
	/**
	 * 爬取章节测试
	 * @param cra
	 * @return
	 * @throws IOException
	 */
	@ResponseBody
	@RequestMapping(value= {"/debug"} ,method = RequestMethod.POST)
	public String debug(@RequestBody CrawlerNovel cra) throws IOException{
		BaseResultDTO re = new BaseResultDTO();
		cra.parse();
		re.setResult(cra);
		re.setSuccess();

		return re.toJSON();
	}
	
	
	
	/**
	 * 发送邮件
	 * @param cra
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/sendMail" )
	public String send(@RequestBody CrawlerNovel cra) throws Exception {
		BaseResultDTO re = new BaseResultDTO();
		Mail.send(cra.getEmail(), "ss","《"+cra.getName()+"》  "+ cra.getTitle(), cra.getContent());
		re.setSuccess();
		return re.toJSON();
	}
	
	
	

	
	/**
	 * 下一页
	 * @param cra
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/nextPage" )
	public String next(@RequestBody CrawlerNovel cra) throws Exception {
		BaseResultDTO re = new BaseResultDTO();
		if(cra.parse().next()){
			if(StringUtils.isNotBlank(cra.getId())){
				novelService.addChapter(cra);
			}
			save(cra);
			re.setResult(cra);
			re.setSuccess();
		}else {
			re.setError("已到最新章节");
		}
		return re.toJSON();
	}
	
	
	
	
	
	/**
	 * 上一页
	 * @param cra
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/prePage" )
	public String pre(@RequestBody CrawlerNovel cra) throws Exception {
		BaseResultDTO re = new BaseResultDTO();

		if(cra.pre()){
			if(StringUtils.isNotBlank(cra.getId())){
				novelService.addChapter(cra);
			}
			save(cra);
			re.setResult(cra);
			re.setSuccess();
		}else {
			re.setError("已到开始章节");
		}
		return re.toJSON();
	}
	

	/**
	 *  下载从选定章节
	 * @throws IOException
	 */
	@RequestMapping(value = "/download" )
	public void download2(CrawlerNovel cra,HttpServletResponse res) throws IOException {

		OutputStream os = res.getOutputStream();
		try {
			String name=URLEncoder.encode(cra.getName(),"utf-8"); //解决中文文件名下载后乱码的问题
			res.setHeader("Content-Disposition", "attachment; filename="+name+".txt");
			res.setContentType("application/octet-stream; charset=utf-8");
			cra.download(os);
			os.flush();
		} finally {
			if (os != null) {
				os.close();
			}
		}
	}
	
	
	/**
	 *  爬取章节目录并保存到本地
	 * @throws Exception 
	 */
	@RequestMapping(value = "/crawler" )
	@ResponseBody
	public String crawler(@RequestBody CrawlerNovel cra) throws Exception {
		BaseResultDTO re = new BaseResultDTO();
        cra.parse();
		while(cra.next()) {
			novelService.addChapter(cra);
			save(cra);
		}
		re.setSuccess();
		return re.toJSON();
	}

	/**
	 * 查询小说章节
	 * @throws Exception
	 */
	@RequestMapping(value = "/queryChapters" )
	@ResponseBody
	public String queryChapters(@RequestBody Map map) throws Exception {
		BaseResultDTO re = new BaseResultDTO();
		JSONObject params = JSONObject.parseObject(JSON.toJSONString(map));

        List<NovelChapter> list = novelService.queryChapters(params);
        re.put("rows", list);
        re.setSuccess();
		return re.toJSON();
	}
	
	
	/**
	 * 查询自动配置
	 * @return
	 */
	@RequestMapping(value = "/queryAutoNovelConfig" )
	@ResponseBody
	public String queryAutoNovelConfig(@RequestBody String reqStr){
		JSONObject reqParams = JSON.parseObject(reqStr);
		String url_fixed = reqParams.getString("url_fixed");
		List<String> list = RegexUtils.match(url_fixed, RegexUtils.REGEX_DOMAIN_NAME);
		BaseResultDTO re = new BaseResultDTO();
		if(list.size()>0){
			String url = list.get(0);
			CrawlerNovel cra = dao.selectOne("novel.queryAutoNovelConfig", url);
			re.setResult(cra);
			re.setSuccess();
		}else {
			re.setError();
		}
		
		return re.toJSON();
	}
	


}
